<?php
/**
 * 推荐文章
 * @author Mortimer He <mortimerhe@163.com>
 */
namespace Manage\Controller;
class FeatureController extends CommonController{
	private $msg=array();
	private $Model;
	private $code='feature';
	function _initialize(){
		parent::_initialize();
		$this->Model=D('Module');
	}
	public function index(){
		if(!$this->checkPermission('FeaturedArticle')) $this->jump();
		$features=$this->Model->getModulesByCode($this->code);
		$this->assign('list',$features);
		$this->display();
	}
	public function oper($module_id=0){
		if(!$module_id && !$this->checkPermission('AddFeaturedArticle')) $this->jump();
		$feature=$this->Model->getModuleById($module_id);
		if($module_id && empty($feature)) $this->jump(L('error_404'));
		if($feature) {
			$feature=json_decode($feature['setting'],true);
		}
		if(IS_POST){
			$feature=I('post.');
			if($this->validateForm()){
				$this->Model->operModule($feature,$this->code,$module_id);
				session('success',$module_id?L('success_edit'):L('success_add'));
				$this->redirect('index');
			}else{
				if(!isset($this->msg['warning'])) $this->msg['warning']=L('error_warning');			
			}
		}
		$articles=array();
		if($feature['article']){
			$ArticleModel=D('Article');
			foreach ($feature['article'] as $article_id) {
				$article_info=$ArticleModel->getArticle($article_id);
				$articles[]=array(
					'article_id'	=>	$article_id,
					'title'			=>	$article_info['article_description'][get_default_lng_id()]['title']
					);
			}
			$feature['article']=$articles;
		}
		$this->assign('languages',get_langs());
		$this->assign('feature',$feature);
		$this->assign('msg',$this->msg);
		$this->display();
	}
	private function validateForm(){
		$module_id=I('get.module_id',0,'trim');
		if($module_id && !$this->checkPermission('EditFeaturedArticle')){
			$this->msg['warning']=L('error_not_permission');
			return !$this->msg;
		}
		$data=I('post.');
		if(mb_strlen($data['name'])>50 || mb_strlen($data['name'])<2){
			$this->msg['name']	=	L('error_name');
		}
		return !$this->msg;
	}
	public function del(){
		if($this->checkPermission('DeleteFeaturedArticle')){
			$module_ids=I('post.selected');
			$count=0;
			foreach ($module_ids as  $module_id) {
				$count += $this->Model->where(array('module_id'=>$module_id))->delete();
			}
			session('success',L('success_delete',array('count'=>$count)));
		}else{
			session('danger',L('error_not_permission'));
		}
		$this->redirect('index');
	}
}